package db

import (
	model "awesomeProject/src/main/Models"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)


func NewDB() *gorm.DB{
	dsn:= "root:root@tcp(localhost:3306)/test?charset=utf8mb4&parseTime=True&loc=Local"
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})

	if err != nil {
		panic(err)
	}

	// 迁移 schema
	db.Debug().AutoMigrate(&model.DemoOrder{})
	return db
}

type OrderDao struct {
	db *gorm.DB
}


func NewOrderDao(db *gorm.DB) *OrderDao {
	return &OrderDao{db: db}
}



//func (orderDao *OrderDao)GetAllOrder() (orderList []*model.DemoOrder, err error){
//	if err = orderDao.db.Find(&orderList).Error; err != nil {
//		return nil, err
//	}
//	return orderList, nil
//}
//func (orderDao *OrderDao)GetAllOrder() (orderList []*model.DemoOrder, err error){
//	if err = orderDao.db.Find(&orderList).Error; err != nil {
//		return nil, err
//	}
//	return orderList, nil
//}
func (o *OrderDao) GetAllOrder() (list []*model.DemoOrder,err error) {
	//操作数据库
	err = o.db.Debug().Find(&list).Error

	if err != nil {
		return nil,err
	}
	return list,nil
}


//新增一条数据
func (o *OrderDao) AddNewOrder(b *model.DemoOrder) (err error) {
	if err = o.db.Debug().Create(&b).Error;err!=nil{
		return err
	}
	return nil
}


//查询一条数据
func (o *OrderDao) GetOneOrder(orderNo string) (b *model.DemoOrder, err error) {
	err = o.db.Debug().First(&b,orderNo).Error

	// SELECT * FROM users WHERE id = 10;
	if err !=nil{
		return b,err
	}
	return b,nil
}

func (o *OrderDao) UpdateOrder(order *model.DemoOrder)(err error){
	err = o.db.Debug().Save(&order).Error
	if err!=nil {
		return err
	}
	return nil
}

func (o *OrderDao)UpdatesOrder(b *model.DemoOrder,updateOrder *model.DemoOrder) (err error){
	if err = o.db.Debug().Model(&b).Updates(updateOrder).Error; err != nil{
		return err
	}
	return nil
}


func (o *OrderDao) DeleteOrder(order *model.DemoOrder) (err error) {
	err = o.db/*.Where("order_no", orderNo)*/.Delete(&order).Error
	if err!=nil{
		return err
	}
	//if err := o.db.Delete(&order).Error;err != nil {
	//	return err
	//}
	//err = dao.DB.Where("id=?",id).Delete(Todo{}).Error  //针对带有DeletedAt会执行软删除

	return nil
}